﻿using LinkingCloud.API.Common.Helper;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

namespace LinkingCloud.API.Common.FileUpload
{
    /// <summary>
    /// 连接远程文件夹
    /// </summary>
    public class FileUploadHelper : IFileUploadHelper
    {
        /// <summary>
        /// 连接远程共享文件夹
        /// </summary>
        /// <param name="path">远程共享文件夹的路径</param>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        public bool ConnectState(string path, string userName, string passWord)
        {
            var flag = false;
            var proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                var dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }

                var errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close(); if (string.IsNullOrEmpty(errormsg))
                {
                    flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }

            return flag;
        }
    }
}
